package tech.yozo.bamboo.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.webkit.WebView;

import androidx.annotation.NonNull;

public class BookView extends WebView {
    private OnSelectedTextListener onSelectedTextListener;

    public BookView(@NonNull Context context) {
        super(context);
    }

    public BookView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public ActionMode startActionMode(ActionMode.Callback callback) {
        ActionMode actionMode = super.startActionMode(callback);
        return resolveActionMode(actionMode);
    }

    @Override
    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
        ActionMode actionMode =  super.startActionMode(callback, type);
        return resolveActionMode(actionMode);
    }

    private ActionMode resolveActionMode(ActionMode actionMode) {
        if (actionMode == null) {
            return null;
        }

        final Menu menu = actionMode.getMenu();
        menu.clear();
        menu.add("More").setOnMenuItemClickListener(item -> {
            getSelectedText();
            return true;
        });

        return actionMode;
    }

    private void getSelectedText() {
        String js = "(function getSelectedText() {var txt;if (window.getSelection) {txt = window.getSelection().toString();} else if (window.document.getSelection) {txt = window.document.getSelection().toString();} else if (window.document.selection) {txt = window.document.selection.createRange().text;}return txt;})()";
        evaluateJavascript("javascript:" + js, value -> {
            Log.i("iReading", "getSelectedText: " + value);
            value = value.replace("\"", "").trim();
            if (value.isEmpty()) {
                return;
            }

            if (onSelectedTextListener != null) {
                onSelectedTextListener.onSelectedText(value);
            }
        });
    }

    public void setOnSelectedTextListener(OnSelectedTextListener onSelectedTextListener) {
        this.onSelectedTextListener = onSelectedTextListener;
    }

    public interface OnSelectedTextListener {
        void onSelectedText(String text);
    }
}
